package com.quant.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.quant.entity.TradeRecord;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonUtils {
	// 初始化Jackson，支持LocalDate
	private static final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());

	// 转换netValueCurveJson为Map<LocalDate, Double>
	public static Map<LocalDate, Double> parseNetValueCurve(String json) {
		if (json == null || json.trim().isEmpty()) {
			return new HashMap<>();
		}
		try {
			return objectMapper.readValue(json, new TypeReference<>() {
			});
		} catch (Exception e) {
			throw new RuntimeException("解析净值曲线失败: " + e.getMessage(), e);
		}
	}

	/**
	 * 解析交易记录JSON数组为List<TradeRecord>
	 *
	 * @param json 数据库中存储的result_json字符串（JSON数组格式）
	 * @return 交易记录列表
	 */
	public static List<TradeRecord> parseTradeRecords(String json) {
		if (json == null || json.trim().isEmpty()) {
			return null;
		}
		try {
			// 关键：使用TypeReference指定泛型类型为List<TradeRecord>
			return objectMapper.readValue(json, new TypeReference<>() {
			});
		} catch (Exception e) {
			throw new RuntimeException("解析交易记录失败: " + e.getMessage(), e);
		}
	}
}
